{% extends "base.html" %}

{% block title %}工具箱 - 单位换算{% endblock %}

{% block extra_css %}
<style>
    .unit-type-tab.active {
        background-color: #ECC94B;
        color: white;
    }
    .decimal-control {
        width: 80px;
    }
</style>
{% endblock %}

{% block content %}
    <!-- 页面标题 -->
    <div class="bg-yellow-500 text-white py-8">
        <div class="container mx-auto px-4">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-3xl font-bold">单位换算</h1>
                    <p class="mt-2">长度、重量、面积、体积、温度等常用单位互换计算器</p>
                </div>
                <div class="bg-white bg-opacity-20 p-4 rounded-lg hidden md:block">
                    <div class="flex space-x-2 text-sm">
                        <a href="{{ url_for('main.index') }}" class="hover:underline">首页</a>
                        <span>/</span>
                        <a href="{{ url_for('converter_tools.index') }}" class="hover:underline">数据转换工具</a>
                        <span>/</span>
                        <span class="font-medium">单位换算</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
        <div class="bg-white rounded-lg shadow-lg overflow-hidden mb-8">
            <!-- 单位类型选择 -->
            <div class="bg-gray-100 p-4 border-b border-gray-200">
                <div class="flex flex-wrap gap-2">
                    {% for type_key, type_data in unit_types.items() %}
                    <button 
                        type="button" 
                        class="unit-type-tab px-4 py-2 rounded-md text-sm font-medium focus:outline-none {% if loop.first %}active{% endif %}" 
                        data-type="{{ type_key }}">
                        {{ type_data.name }}
                    </button>
                    {% endfor %}
                </div>
            </div>
            
            <!-- 转换区域 -->
            <div class="p-6">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
                    <!-- 输入区域 -->
                    <div>
                        <h3 class="text-lg font-medium text-gray-800 mb-4">输入数值</h3>
                        <div class="space-y-4">
                            <div>
                                <label class="block text-gray-700 text-sm font-bold mb-2" for="value">
                                    数值：
                                </label>
                                <input type="number" id="value" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" step="any" value="1">
                            </div>
                            
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-gray-700 text-sm font-bold mb-2" for="from-unit">
                                        从单位：
                                    </label>
                                    <select id="from-unit" class="shadow border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline">
                                        <!-- 选项由JS动态填充 -->
                                    </select>
                                </div>
                                <div>
                                    <label class="block text-gray-700 text-sm font-bold mb-2" for="to-unit">
                                        到单位：
                                    </label>
                                    <select id="to-unit" class="shadow border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline">
                                        <!-- 选项由JS动态填充 -->
                                    </select>
                                </div>
                            </div>
                            
                            <div>
                                <label class="block text-gray-700 text-sm font-bold mb-2" for="decimal-places">
                                    小数位数：
                                </label>
                                <input type="number" id="decimal-places" class="shadow appearance-none border rounded decimal-control py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" min="0" max="10" value="6">
                            </div>
                            
                            <div class="pt-2">
                                <button id="convert-btn" type="button" class="w-full bg-yellow-500 hover:bg-yellow-600 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline transition-colors">
                                    转换
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 结果区域 -->
                    <div>
                        <h3 class="text-lg font-medium text-gray-800 mb-4">转换结果</h3>
                        <div class="bg-gray-100 p-4 rounded-lg">
                            <div class="mb-4">
                                <span id="input-display" class="text-gray-800 font-medium">1</span>
                                <span id="from-unit-display" class="text-gray-600">米</span>
                                <span class="text-gray-800 mx-2">=</span>
                                <span id="result-display" class="text-2xl text-yellow-600 font-bold">1</span>
                                <span id="to-unit-display" class="text-gray-600">米</span>
                            </div>
                            <div id="formula-display" class="text-sm text-gray-500 mb-4">
                                换算公式: 1 米 × 1 = 1 米
                            </div>
                            <div class="flex space-x-2">
                                <button id="copy-btn" type="button" class="bg-gray-200 hover:bg-gray-300 text-gray-800 font-medium py-1 px-3 rounded text-sm focus:outline-none focus:shadow-outline transition-colors">
                                    <i class="far fa-copy mr-1"></i>复制结果
                                </button>
                                <button id="swap-btn" type="button" class="bg-blue-100 hover:bg-blue-200 text-blue-800 font-medium py-1 px-3 rounded text-sm focus:outline-none focus:shadow-outline transition-colors">
                                    <i class="fas fa-exchange-alt mr-1"></i>交换单位
                                </button>
                            </div>
                        </div>
                        
                        <!-- 快速转换表 -->
                        <div class="mt-6">
                            <h4 class="text-md font-medium text-gray-800 mb-3">快速转换表</h4>
                            <div class="bg-gray-50 border border-gray-200 rounded-lg">
                                <table class="w-full">
                                    <thead class="bg-gray-100">
                                        <tr>
                                            <th class="py-2 px-4 text-left text-sm font-medium text-gray-600">单位</th>
                                            <th class="py-2 px-4 text-left text-sm font-medium text-gray-600">转换结果</th>
                                        </tr>
                                    </thead>
                                    <tbody id="quick-conversion-table" class="divide-y divide-gray-200">
                                        <!-- 内容由JS动态填充 -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 转换说明 -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
            <div class="bg-white rounded-lg shadow p-6">
                <h3 class="text-lg font-medium text-gray-800 mb-3">如何使用</h3>
                <ol class="text-gray-600 space-y-2 list-decimal list-inside">
                    <li>选择需要转换的单位类型（长度、重量等）</li>
                    <li>输入数值</li>
                    <li>选择起始单位和目标单位</li>
                    <li>点击"转换"按钮获取结果</li>
                    <li>可以使用"交换单位"快速反向转换</li>
                </ol>
            </div>
            
            <div class="bg-white rounded-lg shadow p-6">
                <h3 class="text-lg font-medium text-gray-800 mb-3">功能特点</h3>
                <ul class="text-gray-600 space-y-2">
                    <li class="flex items-start">
                        <i class="fas fa-check-circle text-green-500 mt-1 mr-2"></i>
                        <span>支持多种单位类型（长度、重量、面积、体积、温度）</span>
                    </li>
                    <li class="flex items-start">
                        <i class="fas fa-check-circle text-green-500 mt-1 mr-2"></i>
                        <span>高精度计算，可自定义小数位数</span>
                    </li>
                    <li class="flex items-start">
                        <i class="fas fa-check-circle text-green-500 mt-1 mr-2"></i>
                        <span>快速生成转换表，便于参考</span>
                    </li>
                </ul>
            </div>
            
            <div class="bg-white rounded-lg shadow p-6">
                <h3 class="text-lg font-medium text-gray-800 mb-3">技巧提示</h3>
                <ul class="text-gray-600 space-y-2">
                    <li class="flex items-start">
                        <i class="fas fa-lightbulb text-yellow-500 mt-1 mr-2"></i>
                        <span>使用Tab键快速在输入框之间切换</span>
                    </li>
                    <li class="flex items-start">
                        <i class="fas fa-lightbulb text-yellow-500 mt-1 mr-2"></i>
                        <span>输入数值后按Enter键可直接触发转换</span>
                    </li>
                    <li class="flex items-start">
                        <i class="fas fa-lightbulb text-yellow-500 mt-1 mr-2"></i>
                        <span>复制结果功能可将转换结果复制到剪贴板</span>
                    </li>
                </ul>
            </div>
        </div>
        
        <!-- 相关工具 -->
        <div class="bg-white rounded-lg shadow p-6">
            <h3 class="text-lg font-medium text-gray-800 mb-4">相关工具</h3>
            <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                <a href="#" class="group">
                    <div class="bg-gray-100 group-hover:bg-yellow-100 rounded-lg p-4 transition-colors">
                        <div class="text-center mb-2">
                            <i class="fas fa-exchange-alt text-yellow-600 text-2xl"></i>
                        </div>
                        <p class="text-center text-gray-700 group-hover:text-gray-900">进制转换</p>
                    </div>
                </a>
                <a href="#" class="group">
                    <div class="bg-gray-100 group-hover:bg-yellow-100 rounded-lg p-4 transition-colors">
                        <div class="text-center mb-2">
                            <i class="fas fa-calendar-alt text-yellow-600 text-2xl"></i>
                        </div>
                        <p class="text-center text-gray-700 group-hover:text-gray-900">日期计算</p>
                    </div>
                </a>
                <a href="#" class="group">
                    <div class="bg-gray-100 group-hover:bg-yellow-100 rounded-lg p-4 transition-colors">
                        <div class="text-center mb-2">
                            <i class="fas fa-money-bill-wave text-yellow-600 text-2xl"></i>
                        </div>
                        <p class="text-center text-gray-700 group-hover:text-gray-900">货币转换</p>
                    </div>
                </a>
                <a href="#" class="group">
                    <div class="bg-gray-100 group-hover:bg-yellow-100 rounded-lg p-4 transition-colors">
                        <div class="text-center mb-2">
                            <i class="fas fa-calculator text-yellow-600 text-2xl"></i>
                        </div>
                        <p class="text-center text-gray-700 group-hover:text-gray-900">科学计算器</p>
                    </div>
                </a>
            </div>
        </div>
    </div>
{% endblock %}

{% block scripts %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 初始化单位类型数据
        const unitTypes = {{ unit_types|tojson }};
        let currentType = Object.keys(unitTypes)[0]; // 默认选择第一个类型
        let decimalPlaces = 6; // 默认小数位数
        
        // DOM元素
        const typeButtons = document.querySelectorAll('.unit-type-tab');
        const valueInput = document.getElementById('value');
        const fromUnitSelect = document.getElementById('from-unit');
        const toUnitSelect = document.getElementById('to-unit');
        const decimalInput = document.getElementById('decimal-places');
        const convertBtn = document.getElementById('convert-btn');
        const swapBtn = document.getElementById('swap-btn');
        const copyBtn = document.getElementById('copy-btn');
        const resultDisplay = document.getElementById('result-display');
        const inputDisplay = document.getElementById('input-display');
        const fromUnitDisplay = document.getElementById('from-unit-display');
        const toUnitDisplay = document.getElementById('to-unit-display');
        const formulaDisplay = document.getElementById('formula-display');
        const quickConversionTable = document.getElementById('quick-conversion-table');
        
        // 初始化页面
        function initPage() {
            // 加载单位选择
            loadUnitOptions();
            
            // 事件监听
            typeButtons.forEach(button => {
                button.addEventListener('click', function() {
                    // 更新选中状态
                    typeButtons.forEach(btn => btn.classList.remove('active'));
                    this.classList.add('active');
                    
                    // 更新当前类型
                    currentType = this.dataset.type;
                    
                    // 重新加载单位选项
                    loadUnitOptions();
                });
            });
            
            // 转换按钮点击事件
            convertBtn.addEventListener('click', performConversion);
            
            // 输入框回车事件
            valueInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    performConversion();
                }
            });
            
            // 小数位数变化事件
            decimalInput.addEventListener('change', function() {
                decimalPlaces = parseInt(this.value) || 6;
                if (decimalPlaces < 0) decimalPlaces = 0;
                if (decimalPlaces > 10) decimalPlaces = 10;
                this.value = decimalPlaces;
                
                // 如果已有结果，更新显示
                if (resultDisplay.textContent !== '1') {
                    performConversion();
                }
            });
            
            // 交换单位按钮点击事件
            swapBtn.addEventListener('click', function() {
                const fromIndex = fromUnitSelect.selectedIndex;
                const toIndex = toUnitSelect.selectedIndex;
                
                fromUnitSelect.selectedIndex = toIndex;
                toUnitSelect.selectedIndex = fromIndex;
                
                performConversion();
            });
            
            // 复制结果按钮点击事件
            copyBtn.addEventListener('click', function() {
                const textToCopy = `${inputDisplay.textContent} ${fromUnitDisplay.textContent} = ${resultDisplay.textContent} ${toUnitDisplay.textContent}`;
                
                navigator.clipboard.writeText(textToCopy).then(() => {
                    // 复制成功提示
                    const originalText = this.innerHTML;
                    this.innerHTML = '<i class="fas fa-check mr-1"></i>已复制';
                    this.classList.remove('bg-gray-200', 'hover:bg-gray-300');
                    this.classList.add('bg-green-200', 'hover:bg-green-300', 'text-green-800');
                    
                    setTimeout(() => {
                        this.innerHTML = originalText;
                        this.classList.remove('bg-green-200', 'hover:bg-green-300', 'text-green-800');
                        this.classList.add('bg-gray-200', 'hover:bg-gray-300');
                    }, 1500);
                }).catch(err => {
                    console.error('复制失败:', err);
                });
            });
            
            // 初始执行一次转换
            performConversion();
        }
        
        // 加载单位选项
        function loadUnitOptions() {
            const units = unitTypes[currentType].units;
            
            // 清空现有选项
            fromUnitSelect.innerHTML = '';
            toUnitSelect.innerHTML = '';
            
            // 添加新选项
            for (const [code, name] of Object.entries(units)) {
                fromUnitSelect.add(new Option(`${name} (${code})`, code));
                toUnitSelect.add(new Option(`${name} (${code})`, code));
            }
            
            // 设置默认值
            if (currentType === 'length') {
                setDefaultOptions('m', 'cm');
            } else if (currentType === 'weight') {
                setDefaultOptions('kg', 'g');
            } else if (currentType === 'area') {
                setDefaultOptions('m2', 'cm2');
            } else if (currentType === 'volume') {
                setDefaultOptions('m3', 'l');
            } else if (currentType === 'temperature') {
                setDefaultOptions('c', 'f');
            }
        }
        
        // 设置默认选择的单位
        function setDefaultOptions(fromUnit, toUnit) {
            for (let i = 0; i < fromUnitSelect.options.length; i++) {
                if (fromUnitSelect.options[i].value === fromUnit) {
                    fromUnitSelect.selectedIndex = i;
                    break;
                }
            }
            
            for (let i = 0; i < toUnitSelect.options.length; i++) {
                if (toUnitSelect.options[i].value === toUnit) {
                    toUnitSelect.selectedIndex = i;
                    break;
                }
            }
        }
        
        // 执行单位转换
        function performConversion() {
            const value = parseFloat(valueInput.value);
            if (isNaN(value)) {
                // 输入值无效
                showError('请输入有效的数值');
                return;
            }
            
            const fromUnit = fromUnitSelect.value;
            const toUnit = toUnitSelect.value;
            
            // 发送转换请求
            fetch('/tools/converter/unit-converter', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    value: value,
                    from_unit: fromUnit,
                    to_unit: toUnit,
                    unit_type: currentType
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.error === 0) {
                    // 更新转换结果
                    updateResult(data);
                    // 生成快速转换表
                    generateQuickConversionTable(value, fromUnit);
                } else {
                    // 显示错误信息
                    showError(data.message);
                }
            })
            .catch(error => {
                showError('转换请求失败，请稍后重试');
                console.error('转换错误:', error);
            });
        }
        
        // 更新转换结果显示
        function updateResult(data) {
            const result = parseFloat(data.result);
            
            // 更新结果显示
            resultDisplay.textContent = result.toFixed(decimalPlaces);
            inputDisplay.textContent = data.value;
            
            // 获取单位的显示名称
            const fromUnitName = unitTypes[currentType].units[data.from_unit];
            const toUnitName = unitTypes[currentType].units[data.to_unit];
            
            fromUnitDisplay.textContent = fromUnitName;
            toUnitDisplay.textContent = toUnitName;
            
            // 更新公式显示
            let formula = `换算公式: `;
            if (currentType === 'temperature') {
                // 温度转换有特殊公式
                if (data.from_unit === 'c' && data.to_unit === 'f') {
                    formula += `${data.value} °C × 9/5 + 32 = ${result.toFixed(decimalPlaces)} °F`;
                } else if (data.from_unit === 'f' && data.to_unit === 'c') {
                    formula += `(${data.value} °F - 32) × 5/9 = ${result.toFixed(decimalPlaces)} °C`;
                } else if (data.from_unit === 'c' && data.to_unit === 'k') {
                    formula += `${data.value} °C + 273.15 = ${result.toFixed(decimalPlaces)} K`;
                } else if (data.from_unit === 'k' && data.to_unit === 'c') {
                    formula += `${data.value} K - 273.15 = ${result.toFixed(decimalPlaces)} °C`;
                } else if (data.from_unit === 'f' && data.to_unit === 'k') {
                    formula += `(${data.value} °F - 32) × 5/9 + 273.15 = ${result.toFixed(decimalPlaces)} K`;
                } else if (data.from_unit === 'k' && data.to_unit === 'f') {
                    formula += `(${data.value} K - 273.15) × 9/5 + 32 = ${result.toFixed(decimalPlaces)} °F`;
                } else {
                    formula += `${data.value} ${fromUnitName} = ${result.toFixed(decimalPlaces)} ${toUnitName}`;
                }
            } else {
                // 普通单位转换
                const factor = result / data.value;
                formula += `${data.value} ${fromUnitName} × ${factor.toFixed(decimalPlaces)} = ${result.toFixed(decimalPlaces)} ${toUnitName}`;
            }
            
            formulaDisplay.textContent = formula;
        }
        
        // 生成快速转换表
        function generateQuickConversionTable(value, fromUnit) {
            // 清空现有表
            quickConversionTable.innerHTML = '';
            
            const units = unitTypes[currentType].units;
            
            for (const [code, name] of Object.entries(units)) {
                if (code === fromUnit) continue; // 跳过当前单位
                
                // 发送转换请求
                fetch('/tools/converter/unit-converter', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        value: value,
                        from_unit: fromUnit,
                        to_unit: code,
                        unit_type: currentType
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.error === 0) {
                        // 添加到表格
                        const result = parseFloat(data.result);
                        
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td class="py-2 px-4 text-sm">${name} (${code})</td>
                            <td class="py-2 px-4 text-sm font-medium">${result.toFixed(decimalPlaces)}</td>
                        `;
                        quickConversionTable.appendChild(row);
                    }
                })
                .catch(error => {
                    console.error('转换错误:', error);
                });
            }
        }
        
        // 显示错误信息
        function showError(message) {
            resultDisplay.textContent = '错误';
            formulaDisplay.textContent = message;
            fromUnitDisplay.textContent = '';
            toUnitDisplay.textContent = '';
        }
        
        // 初始化页面
        initPage();
    });
</script>
{% endblock %} 